const Emitter = require("events");
export class Koa extends Emitter {
  constructor(options) {
    super();
    this.middlewares = [];
    this.context = Object.create();
  }

  use(fn) {
    this.middlewares.push(fn);
  }

  listen() {
    const fnMiddlewares = compose(this.middlewares);
    const ctx = this.context;
    fnMiddlewares(ctx);
  }
}

function compose(fns) {
  if (!Array.isArray(fns)) {
    throw new TypeError("");
  }
  if (fns.some((fn) => typeof fn !== "function")) throw new TypeError("");

  return function (ctx, next) {
    return dispatch(0);
    function dispatch(id) {
      const current = fns[id];
      if (id === fns.length) current = next;
      try {
        return Promise.resolve(current(ctx, dispatch.bind(null, id + 1)));
      } catch (error) {
        return Promise.reject(error);
      }
    }
  };
}
